package com.itheima.springbootwebtlias.filter;

import com.itheima.springbootwebtlias.util.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取请求路径
        /*System.out.println("uri:"+request.getRequestURI());
        System.out.println("url:"+request.getRequestURL());*/
        String url = request.getRequestURI().toString();

        //2.判断请求路径是否为登录请求（办理门禁卡，直接放行）
        //如果是登录请求，直接放行
        if (url.contains("/login")) {
            log.info("登录请求，直接放行");
            filterChain.doFilter(request, response);
            return;//注意：return不能省略
        }

        //3.获取请求头中的令牌（出示门禁卡）
        String jwt = request.getHeader("token");
        if (jwt == null) {
            log.info("没有令牌，请登录...");
            //没有携带令牌（没带门禁卡，禁止进入小区），拦截请求，封装错误结果
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);//401
            return;
        }

        //4.解析令牌，判断令牌是否正确（刷门禁卡）
        try{
            JwtUtils.parseJWT(jwt);
        }catch (Exception e){
            log.info("令牌解析失败，请重新登录...");
            //解析错误（门禁卡失效），封装错误结果
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);//401
            return;

        }

        //5.放行
        log.info("令牌解析成功，放行...");
        filterChain.doFilter(request, response);
    }
}
